<template>
  <ContentWrap>
    <FormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="callCode" label="通话记录编号">
          <el-input v-model.trim="formData.callCode" placeholder="请输入通话记录编号" clearable />
        </el-form-item>
        <el-form-item prop="customerName" label="客户姓名">
          <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item prop="customerPhone" label="联系电话">
          <el-input v-model.trim="formData.customerPhone" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item prop="callType" label="呼叫类型">
          <el-select v-model="formData.callType" placeholder="请选择呼叫类型" filterable clearable>
            <el-option v-for="(c,i) in callTypeList" :key="i" :label="c.dictName" :value="c.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item prop="ivrOption" label="IVR选项">
          <el-select v-model="formData.ivrOption" placeholder="请选择IVR" filterable clearable>
            <el-option v-for="(iv,i) in ivrList" :key="i" :label="iv.dictName" :value="iv.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item prop="workOrderNo" hidden label="工单编号">
          <el-input v-model.trim="formData.workOrderNo" placeholder="请输入工单编号" clearable />
        </el-form-item>
        <el-form-item prop="nickname" label="顾客ID">
          <el-input v-model.trim="formData.nickname" placeholder="请输入顾客ID" clearable />
        </el-form-item>
        <el-form-item prop="callOrderCode" label="订单编号">
          <el-input v-model.trim="formData.callOrderCode" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item prop="callOnlinePlatformCode" label="电商平台">
          <el-select v-model="formData.callOnlinePlatformCode" placeholder="请选择电商平台" remote :remote-method="getPlatformInfo" filterable clearable @change="platfromChange">
            <el-option v-for="(p,i) in platformList" :key="i" :label="p.name" :value="p.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="callOnlineShopCode" label="电商店铺">
          <el-select v-model="formData.callOnlineShopCode" placeholder="请选择电商店铺" remote :remote-method="getStoreInfo" filterable clearable>
            <el-option v-for="(s,i) in shopList" :key="i" :label="s.name" :value="s.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="crmCustomerCode" label="客户编码">
          <el-input v-model.trim="formData.crmCustomerCode" placeholder="请输入客户编码" clearable />
        </el-form-item>
        <el-form-item prop="crmCallObject" label="通话对象">
          <el-select v-model="formData.crmCallObject" placeholder="请选择通话对象" filterable clearable>
            <el-option v-for="(o,i) in telObjectList" :key="i" :value="o.dictCode" :label="o.dictName" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sapCode" label="SAP编码">
          <el-input v-model.trim="formData.sapCode" placeholder="请输入SAP编码" clearable />
        </el-form-item>
        <el-form-item prop="bpmCode" label="BPM编号">
          <el-input v-model.trim="formData.bpmCode" placeholder="请输入BPM编号" clearable />
        </el-form-item>
        <el-form-item prop="department" label="通话部门" :span="12">
          <el-select v-model="formData.department" placeholder="请选择通话部门" multiple :disabled="$isFinance()" filterable clearable @change="changeHandle">
            <el-option v-for="(d,i) in comDepList" :key="i" :label="d.deptName" :value="d.deptNo" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="duration" label="通话时长">
        <el-input v-model="formData.duration" number placeholder="请输入通话时长">
          <span slot="suffix">秒</span>
        </el-input>
      </el-form-item> -->
        <el-form-item prop="maxDuration" label="最大通话时长">
          <el-input v-model="formData.maxDuration" number placeholder="请输入最大通话时长" clearable>
            <span slot="suffix">秒</span>
          </el-input>
        </el-form-item>
        <el-form-item prop="minDuration" label="最小通话时长">
          <el-input v-model="formData.minDuration" number placeholder="请输入最小通话时长" clearable>
            <span slot="suffix">秒</span>
          </el-input>
        </el-form-item>
        <el-form-item prop="groupNo" label="坐席业务组">
          <SearchSelectPicker
            url="/call-center/api/v1/businessGroup/page"
            placeholder="请选择"
            lable-name="groupName"
            value-name="groupNo"
            method="post"
            :value.sync="formData.groupNo"
            :lable.sync="formData.groupName"
            @selectChange="groupNoSelectChange"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="caller" label="坐席姓名">
          <!-- <StaffSearch v-model="formData.caller" placeholder="请选择坐席" clearable /> -->
          <SearchSelectPicker
            url="/call-center/api/v1/staffInfo/page"
            placeholder="请选择"
            :params="{query:{groupNo:formData.groupNo},type:0}"
            lable-name="staffName"
            value-name="accountNo"
            method="post"
            :value.sync="formData.caller"
            :lable.sync="formData.callerName"
            @selectChange="staffSelectChange"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="callerPlatformNo" show label="接听坐席工号">
          <el-input v-model.trim="formData.callerPlatformNo" placeholder="请输入接听坐席工号" clearable />
        </el-form-item>
        <el-form-item prop="localNumber" label="本地号码">
          <el-input v-model.trim="formData.localNumber" placeholder="请输入本地号码" clearable />
        </el-form-item>
        <el-form-item prop="virtualNumber" label="三方虚拟号">
          <el-input v-model.trim="formData.virtualNumber" placeholder="请输入三方虚拟号" clearable />
        </el-form-item>
        <el-form-item prop="prefix" label="呼出前缀">
          <el-input v-model.trim="formData.prefix" placeholder="请输入呼出前缀" clearable />
        </el-form-item>
        <el-form-item prop="extensionNumber" label="分机号">
          <el-input v-model.trim="formData.extensionNumber" placeholder="请输入分机号" clearable />
        </el-form-item>
        <el-form-item prop="satisfaction" label="满意度">
          <el-select v-model="formData.satisfaction" placeholder="请选择满意度" filterable clearable>
            <el-option v-for="(s,i) in satisfaction" :key="i" :label="s.dictName" :value="s.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item prop="evaluateType" label="顾客评价">
          <el-select v-model="formData.evaluateType" placeholder="请选择顾客评价" filterable clearable>
            <el-option v-for="(e,i) in evaluateList" :key="i" :label="e.dictName" :value="e.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item prop="releaseCause" label="挂机原因">
          <el-input v-model.trim="formData.releaseCause" placeholder="请输入挂机原因" clearable />
        </el-form-item>
        <el-form-item prop="callDate" label="通话时间" :span="24/4*1.5">
          <el-date-picker
            v-model="formData.callDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            opt
            :limite="new Date()"
            operator=">"
            clearable
          />
        </el-form-item>
        <el-form-item prop="callSource" label="外呼路径">
          <el-select v-model="formData.callSource" placeholder="请选择外呼路径" filterable clearable>
            <el-option v-for="(c,i) in CALLOUT_TYPE" :key="i" :label="c.dictName" :value="c.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item prop="callPlatform" label="话务平台">
          <SelectForDict
            dict-type-code="CALL_PLATFORM"
            app-code="call-center"
            :code.sync="formData.callPlatform"
            placeholder="请选择话务平台"
          ></SelectForDict>
        </el-form-item>
        <el-form-item show more :span="24/4*1.5">
          <Button @click="resetForm">重置</Button>
          <Button type="primary" enter @click="queryClick">查询</Button>
          <ExportPane :table-config="tableConfig" :fields="exportFields" :query-data-fun="queryClick" filename="通话记录" style="margin-right:10px;margin-left:5px;">导出</ExportPane>
        </el-form-item>
      </el-form>
    </FormContainer>
    <slot></slot>
  </ContentWrap>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import ContentWrap from '@/components/ContentWrap'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import SelectForDict from '@/components/SelectForDict'
import { filtersRaw, strToNumber } from '@/utils'
import { ccDict } from '@/api/dataDict'
import { getDepartmentInfo } from '@/api/department'
import { parseTime, currDatePeriod, date24 } from '@/utils'
import { mapGetters } from 'vuex'
import { getPlatformInfo, getStoreInfo, getBusinessGroup } from '@/api/mscInfo'
import ExportPane from '@/components/ExportPane'
export default {
  name: 'CallQuery',
  components: {
    FormContainer,
    ContentWrap,
    Button,
    ExportPane,
    SearchSelectPicker,
    SelectForDict
  },
  data() {
    // 验证通话日期
    const validateCallDate = (r, v, c) => {
      if (v && v.length > 1) {
        c()
      } else {
        c(new Error('请选择通话时间'))
      }
    }
    return {
      formData: {
        callCode: '', // 通话记录编号
        customerName: '', // 客户姓名
        customerPhone: '', // 联系电话
        callType: '', // 呼叫类型
        ivrOption: '', // ivrOption
        workOrderNo: '', // 工单编号
        nickname: '', // 顾客ID
        callOrderCode: '', // 订单编号
        callOnlinePlatformCode: '', // 电商平台
        callOnlineShopCode: '', // 电商店铺
        crmCustomerCode: '', // 客户编码
        crmCallObject: '', // 通话对象
        sapCode: '', // SAP编码
        bpmCode: '', // BPM编号
        department: [], // 通话部门
        // duration: '', // 通话时长
        maxDuration: '', // 最大通话时长
        minDuration: '', // 最小通话时长
        groupNo: '', // 坐席业务组编码
        groupName: '', // 坐席业务组姓名
        caller: '', // 坐席姓名
        callerPlatformNo: '',
        localNumber: '', // 本地号码
        virtualNumber: '', // 虚拟号
        prefix: '', // 呼出前缀
        extensionNumber: '', // 分机号
        releaseCause: '', // 挂机原因
        satisfaction: '', // 满意度
        evaluateType: '', // 顾客评价
        callDate: this.getDefDate(), // 通话时间
        callSource: '' // TODO:外呼路径
      },
      formRules: {
        callDate: [{ required: true, validator: validateCallDate, trigger: 'change' }]
      },
      telObjectList: [],
      callTypeList: [], // 呼叫类型
      depList: [], // 部门
      satisfaction: [], // 满意度
      evaluateList: [], // 顾客评价
      ivrList: [], // ivr选项
      CALLOUT_TYPE: [], // 外呼路径
      platformList: [],
      shopList: [],
      // 导出相关
      tableConfig: {
        interfacePath: '/call-center/api/v1/callLog/page',
        sort: 'callDate',
        order: 'desc',
        setting: []
      },
      exportFields: {
        callCode: '通话记录编号',
        customerName: '客户姓名',
        customerPhone: '联系电话',
        callType: {
          label: '呼叫类型',
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'CALL_TYPE'
          }
        },
        workOrderNo: '工单编号',
        callSource: {
          label: '外呼路径',
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'CALLOUT_TYPE'
          }
        },
        content: '外呼事宜',
        callDate: '通话时间',
        talkTime: '通话时长',
        callerName: {
          label: '接听坐席',
          formatData: v => {
            let str = `${v.callerName}(${v.createBy})`
            if (v.callerPlatformNo) {
              str += ` - ${v.callerPlatformNo}`
            }
            return str
          }
        },
        satisfaction: {
          label: '满意度',
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'SATISFACTION'
          }
        },
        evaluateType: {
          label: '顾客评价',
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'EVALUATE_STAFF'
          }
        },
        localNumber: '本地号码',
        extensionNumber: '分机',
        prefix: '外呼前缀',
        virtualNumber: '三方虚拟号'
      }
    }
  },
  computed: {
    ...mapGetters(['firstDept', 'accountNo', 'staffName']),
    comDepList() {
      // return this.depList
      const t = [this.$client, this.$sale, this.$sale3, this.$shop, this.$customerCare, this.$customerManagement]
      if (this.$isFinance()) {
        return this.depList.filter(e => {
          return e.deptNo === this.$finance
        })
      } else {
        return this.depList.filter(e => {
          return e.deptNo !== this.$finance && t.includes(e.deptNo)
        })
      }
    }
  },
  created() {
    this.getSelectList()
    if (this.$route.query.callTel) {
      this.$set(this.formData, 'customerPhone', this.$route.query.callTel)
    }
    if (this.$route.query.callCode) {
      this.$set(this.formData, 'callCode', this.$route.query.callCode)
    }
    // 设置通话部门为当前登录用户部门
    this.$set(this.formData, 'department', [this.firstDept])
    // 默认查询自己的通话记录
    this.$set(this.formData, 'caller', this.accountNo)
    this.$set(this.formData, 'callerName', this.staffName)
    this.staffSelectChange({ accountNo: this.accountNo })

    this.getPlatformInfo('')
  },
  methods: {
    // 选择全部时展示全部组件
    changeHandle(v) {
      this.$emit('showAll', v && v.length > 1)
    },
    // 当日零时
    getDefDate() {
      return currDatePeriod()
    },
    queryClick(type) {
      return this.$refs.form.validate().then(() => {
        // const eq = ['callType','ivrOption','callOnlinePlatformCode','callOnlineShopCode','crmCallObject','department','satisfaction','evaluateType']
        const likeList = ['customerName']
        const filtersQueryRaw = []
        for (const key of Object.keys(this.formData)) {
          let v = this.formData[key]
          if (!v) continue
          if (key === 'callDate') {
            filtersQueryRaw.push(filtersRaw(key, parseTime(v[0]), '>'))
            filtersQueryRaw.push(filtersRaw(key, parseTime(date24(v[1])), '<='))
          } else if (key === 'maxDuration') {
            filtersQueryRaw.push(filtersRaw('talkTime', v, '<'))
          } else if (key === 'minDuration') {
            filtersQueryRaw.push(filtersRaw('talkTime', v, '>'))
          } else if (likeList.includes(key)) {
            filtersQueryRaw.push(filtersRaw(key, v, 'like'))
          } else if (key === 'department') {
            // if (!v || v.length <= 0) {
            //   v = [this.firstDept]
            // }
            if (v.length <= 0) {
              continue
            }
            v = v.map(e => strToNumber(e))
            filtersQueryRaw.push(filtersRaw(key, v, 'in'))
          } else if (['callerName', 'groupName'].includes(key)) {
            continue
          } else {
            filtersQueryRaw.push(filtersRaw(key, v, '='))
          }
        }
        // this.queryData(this.$children, [])
        if (type !== 'export') {
          this.queryData(this.$children, filtersQueryRaw)
        }
        return filtersQueryRaw
      })
    },
    queryData(children, filtersQueryRaw) {
      for (const item of children) {
        if (item.initData instanceof Function) {
          item.initData(filtersQueryRaw)
        }
        if (item.$children) {
          this.queryData(item.$children, filtersQueryRaw)
        }
      }
    },
    // 获取通话对象
    getSelectList() {
      ccDict('CALLING_OBJECT').then(res => {
        this.telObjectList = res.data
      })
      ccDict('CALL_TYPE').then(res => {
        this.callTypeList = res.data
      })
      getDepartmentInfo().then(res => {
        // const all = {
        //   deptName: '全部',
        //   deptNo: ''
        // }
        // this.depList = [all, ...res.data]
        this.depList = res.data
      })
      ccDict('SATISFACTION').then(res => {
        this.satisfaction = res.data
      })
      ccDict('EVALUATE_STAFF').then(res => {
        this.evaluateList = res.data
      })
      ccDict('IVR_OPTIONS').then(res => {
        this.ivrList = res.data
      })
      ccDict('CALLOUT_TYPE').then(res => {
        this.CALLOUT_TYPE = res.data
      })
    },
    // 重置
    resetForm() {
      this.$refs.form.resetFields()
      this.staffSelectChange({ accountNo: this.accountNo })
    },
    // 获取平台信息
    getPlatformInfo(v) {
      const data = {
        name: v
      }
      getPlatformInfo(data).then(res => {
        this.platformList = res.data.records
        this.shopList = []
      })
    },
    // 平台变化
    platfromChange() {
      this.getStoreInfo()
      this.$set(this.formData, 'callOnlineShopCode', '')
    },
    // 业务组值改变时
    groupNoSelectChange(data) {
      setTimeout(() => { this.$refs['form'].validateField(['groupNo']) }, 0)
      this.resetgroupName()
    },
    // 坐席值改变时
    staffSelectChange(data) {
      setTimeout(() => { this.$refs['form'].validateField(['caller']) }, 0)
      // this.resetDisName()
      if (!this.formData.groupNo && data && data.accountNo) this.findGroupInfo(data.accountNo)
    },
    findGroupInfo(data) {
      getBusinessGroup(data).then(res => {
        if (res.success === 1) {
          console.log('res', res.data)
          this.formData.groupName = res.data[0].groupName
          this.formData.groupNo = res.data[0].groupNo
        }
      })
    },
    resetgroupName() {
      this.$set(this.formData, 'caller', '')
      // this.$set(this.formData, 'disName', '')
    },
    // 获取店铺信息
    getStoreInfo(v) {
      const data = {
        name: v,
        pcode: this.formData.callOnlinePlatformCode
      }
      getStoreInfo(data).then(res => {
        this.shopList = res.data.records
      })
    }
  }
}
</script>
<style lang='scss' module>
</style>
